package org.example.new_hbps_backend_reconstruction.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.new_hbps_backend_reconstruction.utils.UserHolder;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 丁利军
 * @date 2025年10月10日 13:16
 * @description 登录拦截器
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 OPTIONS 请求
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return true;
        }

        // 判断用户是否登录（ThreadLocal 中有无用户）
        if (UserHolder.getUser() == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "请先登录11111");
            return false;
        }
        // 放行
        return true;
    }
}
